package com.znyj.cloud.device.task;

import com.znyj.cloud.device.task.model.AbstractTaskModel;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by gaoliwei on 15-3-3.
 */
abstract class AbstractTaskMapping<T extends AbstractTaskModel> {

    protected final Map<String, List<T>> taskMap = new ConcurrentHashMap<>();

    public void removeDevice(String deviceId) {
        taskMap.remove(deviceId);
    }

    public List<T> getTaskQueue(String deviceId) {
        return taskMap.get(deviceId);
    }

    public void add(String deviceId, T task) {

        //如果没有这个deviceid的tasklist则添加一个list
        if (!taskMap.containsKey(deviceId)) {
            List<T> tasks = Collections.synchronizedList(new ArrayList<T>());
            taskMap.put(deviceId, tasks);
        }
        taskMap.get(deviceId).add(task);
    }

    public void remove(String deviceId, long taskId) {
        List<T> taskList = taskMap.get(deviceId);

        if (null == taskList) {
            return;
        }

        for (Iterator<T> iterator = taskList.iterator(); iterator.hasNext(); ) {
            T task = iterator.next();
            if (taskId == task.getTaskId()) {
                iterator.remove();
                break;
            }
        }

        if (taskList.size() <= 0) {
            taskMap.remove(deviceId);
        }
    }

    protected void remove(String deviceId, T task) {
        List<T> tasks = taskMap.get(deviceId);

        if (tasks == null) {
            return;
        }

        tasks.remove(task);

        if (tasks.size() <= 0) {
            taskMap.remove(deviceId);
        }

    }

    public abstract void sendTasks();

}